# !/usr/bin/env python
# -*- coding:utf-8 -*-
# @FileName  :news.py
# @Time      :2022/6/6 19:36
# @Author    :张志坤

from flask_restful import Api, reqparse, Resource, marshal
from flask import g, request, jsonify, json, Blueprint
from models.user import *
from models import db
from common.utils.login_utils import login_required
from common.model_fields.user import news_fields

news_bp = Blueprint("news_bp", __name__)
api = Api(news_bp)


# 文章新增 查询
class AddNewBasic(Resource):
    @login_required
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('channel_id')  # 频道
        parser.add_argument('title')  # 标题
        parser.add_argument('cover')  # 封面
        parser.add_argument('content')  # 内容
        parser.add_argument('user_id')  # 用户id

        args = parser.parse_args()
        # user_id = g.user_id  # 用户id
        channel_id = args['channel_id']  # 频道id
        title = args['title']  # 文章标题
        cover = args['cover']  # 封面
        content = args['content']  # 内容
        user_id = args['user_id']  # 用户id
        if not all([user_id, channel_id, title, cover, content]):
            return jsonify(msg="请补全必填数据", code=400)
        channel = Channel.query.filter_by(cid=channel_id).first()
        if not channel:
            return jsonify(msg="频道不存在", code=400)
        try:
            new = News(user_id=user_id,
                       channel_id=channel_id,
                       title=title,
                       cover=cover,
                       content=content
                       )
            db.session.add(new)
        except Exception as e:
            print("发布文章失败", e)
            return jsonify(msg='发布文章失败', code=400)
        # 成功  保存
        db.session.commit()
        return jsonify(msg='发布文章成功', code=200)

    @login_required
    def get(self):
        try:
            news = News.query.filter_by(user_id=g.user_id).all()
            data = marshal(news, news_fields)
            return jsonify(msg="获取成功", code=200, data=data)
        except Exception as e:
            print("查询该用户下所有的文章报错", e)
            return jsonify(msg='获取失败', code=400)


# 文章的删改查一个
class NewsBasicUpDelSel(Resource):
    @login_required
    def delete(self, nid):
        """
        删除文章   逻辑删除.....
        作者  或者 管理员可以删   这里 只写作者
        """
        # 根据文章id  以及  g对象中的user_id(用户id)   获取文章对象    delete 删除....
        try:
            News.query.filter_by(nid=nid, user_id=g.user_id).first().delete()
        except Exception as e:
            print("删除文章错误", e)
            return jsonify(msg="删除文章失败", code=400)
        # 删除成功保存
        db.session.commit()
        return jsonify(msg="删除文章成功", code=200)

    @login_required
    def patch(self, nid):
        """patch  该请求是修改局部字段"""
        parser = reqparse.RequestParser()
        parser.add_argument('channel_id')  # 频道
        parser.add_argument('title')  # 标题
        parser.add_argument('cover')  # 封面
        parser.add_argument('content')  # 内容

        args = parser.parse_args()
        user_id = g.user_id  # 用户id
        channel_id = args['channel_id']  # 频道id
        title = args['title']  # 文章标题
        cover = args['cover']  # 封面
        content = args['content']  # 内容
        # 只有作者才能修改
        try:
            News.query.filter_by(nid=nid, user_id=user_id).update(
                user_id=user_id,
                channel_id=channel_id,
                title=title,
                cover=cover,
                content=content
            )
        except Exception as e:
            print("修改文章报错", e)
            return jsonify(msg="修改失败", code=400)
        db.session.commit()
        return jsonify(msg="修改成功", code=200)

    @login_required
    def get(self, nid):
        try:
            new = News.query.filter_by(nid=nid).first()
            new_data = marshal(new, news_fields)
        except Exception as e:
            print("查询单个的错误", e)
            return jsonify(msg="查询失败", code=400)

        return jsonify(msg='查询成功', code=200, data=new_data)


# 文章新增 查询
api.add_resource(AddNewBasic, "/create_new")
# 删改 文章
api.add_resource(NewsBasicUpDelSel, "/admin_new/<int:nid>")
